﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Wpf2.Models;
using Wpf2.Views;
using WPFServices;

namespace Wpf2.ViewModels
{
    class editImportOrderViewModel : PropertyChangedBase
    {
        int _iOrderID;
        bool _isSaved = false;
        bool _isChanged = false;
        bool _isMarcle;

        
        decimal totalPayment = 0;

        USER user = new USER();
        StoreInfomation storeInfo = new StoreInfomation();
        ObservableCollection<Products> obsProducts = new ObservableCollection<Products>();
        ObservableCollection<Products> listProducts = new ObservableCollection<Products>();
        ObservableCollection<Products> newListProducts = new ObservableCollection<Products>();

        public editImportOrderViewModel(int iOrderID)
        {
            IOrderID = iOrderID;
            getOrderDetail(iOrderID);
            getListProducts();
            initializeCommand();
        }

    #region --- get; set; ---

        public bool IsSaved
        {
            get { return _isSaved; }
            set { _isSaved = value; }
        }
        public int IOrderID
        {
            get { return _iOrderID; }
            set { _iOrderID = value; }
        }

        public bool IsMarcle
        {
            get { return _isMarcle; }
            set { _isMarcle = value; }
        }

        public bool IsChanged
        {
            get { return _isChanged; }
            set { _isChanged = value; }
        }
        public USER User
        {
            get { return user; }
            set { user = value; }
        }
        public decimal TotalPayment
        {
            get { return totalPayment; }
            set { totalPayment = value; OnPropertyChanged("TotalPayment"); }
        }
        public StoreInfomation StoreInfo
        {
            get { return storeInfo; }
            set { storeInfo = value; }
        }
        public ICommand SaveOrderCommand { get; set; }
        public ICommand PrintOrderCommand { get; set; }
        public ObservableCollection<Products> ObsProducts
        {
            get { return obsProducts; }
            set { obsProducts = value; }
        }
        public ObservableCollection<Products> ListProducts
        {
            get { return listProducts; }
            set { listProducts = value; }
        }
        public ObservableCollection<Products> NewListProducts
        {
            get { return newListProducts; }
            set { newListProducts = value; }
        }

    #endregion

        private void getOrderDetail(int iOrderID)
        {
            IOrderID = iOrderID;
            ORDER ordInfo = WPFServices.Services.Orders.GetOrderByID(iOrderID);
            User.ID_USER = ordInfo.ID_USER;
            IsMarcle = ordInfo.ORDER_TYPES == 1 ? true : false;
            var list = WPFServices.Services.OrderDetails.GetListByOrderID(iOrderID).Select(
                x => new Products()
                {
                    ProductIdAuto = x.PRODUCT.ID_PRO_AUTO,
                    ProductId = x.PRODUCT.ID_PRO,
                    ProductName = x.PRODUCT.NAME_PRO,
                    ProductDescription = x.PRODUCT.DESCRIPTIONS,
                    InventoryCount = x.QUANTITY.Value,
                    CostPrice = x.PRODUCT.DETAILS_PRODUCTS.COST_PRICES.Value,// fai thuc hiện trước IsMarcle
                    // thêm mới ngày 11/5 để thêm chức năng Đá hoa cương
                    ProductHeight = x.HEIGHT ?? 0,
                    ProductWidth = x.WIDTH ?? 0,
                    ProductM2 = x.M2 ?? 0,
                    IsMarble = IsMarcle,

                    
                    UnitName = x.PRODUCT.DETAILS_PRODUCTS.UNIT.NAME_UNIT,
                    CatalogName = x.PRODUCT.CATALOG.NAME_CATALOG

                });
            foreach (Products pro in list)
            {
                // tinh tong tien
                TotalPayment += pro.TotalInPayment;
                ListProducts.Add(pro);
            }
        }

        private void getListProducts()
        {
            var listProducts = WPFServices.Services.Products.GetListProducts().Select(
                x => new Products
                {
                    ProductIdAuto = x.ID_PRO_AUTO,
                    ProductId = x.ID_PRO,
                    ProductName = x.NAME_PRO,
                    ProductDescription = x.DESCRIPTIONS,
                    InventoryCount = (int)x.DETAILS_PRODUCTS.INVENTORY_COUNT,
                    CostPrice = (decimal)x.DETAILS_PRODUCTS.COST_PRICES,
                    Unit = new Unit { UnitID = x.DETAILS_PRODUCTS.UNIT.ID_UNIT, UnitName = x.DETAILS_PRODUCTS.UNIT.NAME_UNIT, UnitNote = x.DETAILS_PRODUCTS.UNIT.NOTES_UNIT },
                    catalog = new Catalogs { CatalogName = x.CATALOG.NAME_CATALOG, CatalogNotes = x.CATALOG.NOTES_CATALOG, IDCatalog = x.CATALOG.ID_CATALOG }
                });
            foreach (Products p in listProducts)
                obsProducts.Add(p);
            addNewProduct();
        }

        /// <summary>
        /// thêm mới 1 Product vào danh sách
        /// </summary>
        public void addNewProduct()
        {
            Products pro = new Products();
            IsSaved = false;
            //IsChanged = true;
            ListProducts.Add(pro);
            NewListProducts.Add(pro);
        }

        public void caculationPaymentForAllProduct()
        {
            TotalPayment = 0;
            foreach (Products pro in ListProducts)
                if (!string.IsNullOrEmpty(pro.ProductId))
                    TotalPayment += pro.TotalInPayment;
        }

        #region --- Command ---

        private void initializeCommand()
        {
            SaveOrderCommand = new RelayCommand<object>
                (
                    canExcutedSaveFunction,
                    saveOrder
                );
            PrintOrderCommand = new RelayCommand<object>
                (
                    canExcutedPrintFunction,
                    printOrder
                );
        }

        private bool canExcutedPrintFunction(object obj)
        {
            return IsSaved;
        }

        private void saveOrder(object obj)
        {
            List<ORDER_DETAILS> orDetailLists = new List<ORDER_DETAILS>();
            foreach (Products pro in ListProducts)
            {
                ORDER_DETAILS ord = new ORDER_DETAILS()
                {

                    ID_ORD = IOrderID,
                    ID_PRO_AUTO = pro.ProductIdAuto,
                    QUANTITY = pro.InventoryCount,
                    HEIGHT = pro.ProductHeight,
                    WIDTH = pro.ProductWidth,
                    M2 = pro.ProductM2
                };
                orDetailLists.Add(ord);
            }
            WPFServices.Services.Orders.UpdateOrder(new ORDER() { ID_ORD = IOrderID, TOTAL = TotalPayment, ID_USER = User.ID_USER??0});
            WPFServices.Services.OrderDetails.UpdateOrderDetail(orDetailLists, false, IsMarcle);
            IsSaved = true;
            IsChanged = false;
            NewListProducts = new ObservableCollection<Products>();
            NewListProducts.Add(ListProducts[ListProducts.Count - 1]);
            MessageBox.Show("Lưu thành công");
        }

        public void printOrder(object o)
        {
            ORDER or = WPFServices.Services.Orders.GetOrderByID(IOrderID);
            IDictionary<string, string> _param = new Dictionary<string, string>();
            _param.Add("StoreName", StoreInfo.StoreName);
            _param.Add("Address", StoreInfo.Address);
            _param.Add("Phone", StoreInfo.Phone);
            _param.Add("Mobile", StoreInfo.Mobile);

            //tạm thời cho parameter cuối là false
            var cryRep = new FormCrystalReportAddInventory(removeAllNullProduct(ListProducts), or.DATE_ORD.Value, _param, IsMarcle);
            cryRep.ShowDialog();
        }

        /// <summary>
        /// Xóa product Null
        /// </summary>
        /// <returns></returns>
        public ObservableCollection<Products> removeAllNullProduct(ObservableCollection<Products> listToRemove)
        {
            ObservableCollection<Products> newList = new ObservableCollection<Products>();
            foreach (Products pro in listToRemove)
                if (pro.ProductIdAuto > 0)
                    newList.Add(pro);
            return newList;
        }

        public bool canExcutedSaveFunction(object obj)
        {
            if (!isExistProduct())
                return false;
            return true;
        }

        private bool isExistProduct()
        {
            if (IsChanged)
                return IsChanged;
            foreach (Products pro in NewListProducts)
            {
                if (pro.ProductIdAuto > 0 && pro.InventoryCount > 0)
                {
                    IsChanged = true;
                    return IsChanged;
                }
            }
            IsChanged = false;
            return IsChanged;
        }

        #endregion
    }
}
